package com.chenshuang.web;

import com.chenshuang.bean.CartGoods;
import com.chenshuang.bean.Goods;
import com.chenshuang.service.GoodsService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebServlet(name = "DeleteServlet", value = "/delete")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取cart.jsp页面的ID
        String id = request.getParameter("id");
        // 创建Session对象
        HttpSession session = request.getSession();


        GoodsService goodsService = new GoodsService();
        Goods goods = goodsService.queryGoods(id);

        // 从共享域中获取商品对象集合
        List<CartGoods> cartgoodslist = (List<CartGoods>) session.getAttribute("cartlist");
        System.out.println("1-----");
        for (CartGoods cg : cartgoodslist) {
            System.out.println("================= 外");
            if(goods.equals(cg.getGoods())){
                // 从集合中根据cartgoods对象删除
                System.out.println("================ 内");
                cartgoodslist.remove(cg);
                break;
            }
        }

        System.out.println(Arrays.toString(cartgoodslist.toArray()));
        //上传共享域
        session.setAttribute("cartlist",cartgoodslist);

        // 转发 到 购物车页面
        request.getRequestDispatcher("cart.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
